package com.example.twoscroolview.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.graphics.plus
import kotlin.jvm.JvmOverloads
import android.graphics.PathMeasure




class FinishRelativeLayout : RelativeLayout {
    private var ivFish: ImageView?=null

    //水波纹
    var ripple =0f
    set(value) {
        field = value
        System.out.println("field====$field")
        rippleAlpha = (100 *(1-field)).toInt()
    }
    //水波纹的透明度
    var rippleAlpha = 0
    var mPaint = Paint()
    //触摸点
    var touchX = 0f
    var touchY = 0f

    val fishDrawable by lazy {
        FishDrawable()
    }

    constructor(context: Context) : super(context) {
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    init {
        init()
    }

    private fun init() {
        setWillNotDraw(false)
        mPaint = Paint()
        mPaint?.isAntiAlias = true
        mPaint?.isDither = true
        mPaint.color=Color.RED
        mPaint.strokeWidth=8f
        mPaint?.style = Paint.Style.STROKE
         ivFish = ImageView(context)
        val layoutParams =
            ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        ivFish?.layoutParams = layoutParams

        ivFish?.setImageDrawable(fishDrawable)
        addView(ivFish)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        mPaint.alpha = rippleAlpha
        canvas?.drawCircle(touchX,touchY,ripple*150,mPaint)
        invalidate()
    }
    override fun onTouchEvent(event: MotionEvent): Boolean {
        touchX = event?.x
        touchY = event?.y
        mPaint.alpha=100
        val objectAnimator = ObjectAnimator.ofFloat(this, "ripple",0f,1f).setDuration(1000)
        objectAnimator.start()

        makeTrail()
        return super.onTouchEvent(event)
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun makeTrail() {
        // 鱼中心的相对坐标
        val fishRelative = fishDrawable.mMiddlePoint
        val headRelative = fishDrawable.headPoint
        //鱼中心的绝对坐标 起始点
        val fishMiddle = PointF(ivFish?.x!!.plus(fishRelative?.x!!),ivFish?.y!!.plus(fishRelative?.y))
        // yutou 控制点1
        val fishHead = PointF(ivFish?.x!!.plus(headRelative?.x!!),ivFish?.y!!.plus(headRelative?.y))
        // 点击坐标 结束点
        val touch = PointF(touchX,touchY)
        val angle = includeAngle(fishMiddle,fishHead,touch)/2
        val delta = includeAngle(fishMiddle, PointF(fishMiddle.x+1,fishMiddle.y),fishHead)

            // 控制点2
        val controlPoint = fishDrawable.calculatePoint(fishMiddle,
        fishDrawable.HEAD_RADIUS*1.6f,angle+delta)
        val path = Path()
        path.moveTo(fishMiddle.x-fishRelative.x,fishMiddle.y-fishRelative.y)
        //绘制三阶贝塞尔曲线
        path.cubicTo(fishHead.x-fishRelative.x,fishHead.y-fishRelative.y,controlPoint.x-fishRelative.x,controlPoint.y-fishRelative.y,touchX-fishRelative.x,touchY-fishRelative.y)

      val animator =   ObjectAnimator.ofFloat(ivFish,"x","y",path)

        animator.addListener(object :AnimatorListenerAdapter(){
            override fun onAnimationEnd(animation: Animator?) {
                super.onAnimationEnd(animation)
                fishDrawable.frequence = 1f
            }

            override fun onAnimationStart(animation: Animator?) {

                super.onAnimationStart(animation)
                fishDrawable.frequence = 11f
            }
        })
        val pathMeasure = PathMeasure(path, false)
        val tan = FloatArray(2)
        animator.addUpdateListener(AnimatorUpdateListener { animation -> //                animation.getAnimatedValue();
            // 执行了整个周期的百分之多少
            val fraction = animation.animatedFraction
            pathMeasure.getPosTan(pathMeasure.length * fraction, null, tan) //tan的意义在下文有解释
            val angle = Math.toDegrees(
                Math.atan2(
                    (-tan[1]).toDouble(),
                    tan[0].toDouble()
                )
            ).toFloat()
            fishDrawable.mFishMainAngle =angle
        })


        animator.setDuration(2000)
        animator.start()
    }
    fun includeAngle(O: PointF, A: PointF, B: PointF): Float {
        // cosAOB
        // OA*OB=(Ax-Ox)(Bx-Ox)+(Ay-Oy)*(By-Oy)
        val AOB = (A.x - O.x) * (B.x - O.x) + (A.y - O.y) * (B.y - O.y)
        val OALength =
            Math.sqrt(((A.x - O.x) * (A.x - O.x) + (A.y - O.y) * (A.y - O.y)).toDouble()).toFloat()
        // OB 的长度
        val OBLength =
            Math.sqrt(((B.x - O.x) * (B.x - O.x) + (B.y - O.y) * (B.y - O.y)).toDouble()).toFloat()
        val cosAOB = AOB / (OALength * OBLength)

        // 反余弦
        val angleAOB = Math.toDegrees(Math.acos(cosAOB.toDouble())).toFloat()

        // AB连线与X的夹角的tan值 - OB与x轴的夹角的tan值
        val direction = (A.y - B.y) / (A.x - B.x) - (O.y - B.y) / (O.x - B.x)
        return if (direction == 0f) {
            if (AOB >= 0) {
                0f
            } else {
                180f
            }
        } else {
            if (direction > 0) {
                -angleAOB
            } else {
                angleAOB
            }
        }
    }
}